package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author ZhangYuJie
 * projectName:shop_manage
 * time:2022/5/16 14:20
 * description:
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        DtsAdmin admin=(DtsAdmin)principals.getPrimaryPrincipal();
        Integer[] roleIds = admin.getRoleIds();

        Set<String> roles = roleService.findRoleByIds(roleIds);
        Set<String> perms = permissionService.findPermByIds(roleIds);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String  username= (String) token.getPrincipal();
        String password = new String ((char[])token.getCredentials());

        DtsAdmin admin=adminService.findByUsername(username);

        if(admin==null){
            throw new UnknownAccountException("未知的账号");
        }
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        if(admin.getPassword()==null||!passwordEncoder.matches(password, admin.getPassword())){
            throw new CredentialsException("密码错误");
        }
        if(admin.getDeleted()){
            throw new LockedAccountException("账号被锁定");
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin  ,password, admin.getUsername());
        return authenticationInfo;
    }
}
